Function Reference

_ReplaceStringInFile

Replaces a string with another string in the given text file (binary won't work!)

#include <File.au3>
_ReplaceStringInFile($szFileName, $szSearchString, $szReplaceString, $fCaseness = 0, $fOccurance = 1)

 

Parameters

$szFileName name of the file to open. ATTENTION !! Needs the FULL path, not just the name returned by eg. FileFindNextFile
$szSearchString The string we want to replace in the file
$szReplaceString The string we want as a replacement for $szSearchString
$fCaseness 0 = Not Case sensitive (default), 1 = Case sensitive, case does matter
$fOccurance 0 = Only first found is replaced, 1 = ALL occurrences are replaced (default)

 

Return Value

Success: Returns the number of occurrences of $szSearchString we found
Failure: Returns -1 and sets @error
@error=1 - Cannot open file
@error=2 - Cannot open temp file
@error=3 - Cannot write to temp file
@error=4 - Cannot delete original file
@error=5 - Cannot rename/move temp file

 

Remarks

None.

 

Related

None.

 

Example


#include <File.au3>

$find = "BEFORE"
$replace = "AFTER"

$filename = "C:\_ReplaceStringInFile.test"

$msg = "Hello Test " & $find & " Hello Test" & @CRLF
$msg &= "Hello Test" & @CRLF
$msg &= @CRLF
$msg &= $find

FileWrite($filename, $msg )
   
msgbox(0,"BEFORE",$msg)

$retval = _ReplaceStringInFile($filename,$find,$replace)
if $retval = -1 then
    msgbox(0, "ERROR", "The pattern could not be replaced in file: " & $filename & " Error: " & @error)
    exit
else
    msgbox(0, "INFO", "Found " & $retval & " occurances of the pattern: " & $find & " in the file: " & $filename)
endif

$msg = FileRead($filename, 1000)
msgbox(0,"AFTER",$msg)
FileDelete($filename)